package net.csdn.business.common.feign.config;

import feign.FeignException;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.domain.ApiErrorResult;
import net.csdn.business.common.enums.ResultCodeEnum;
import net.csdn.business.common.exception.BusinessException;
import net.csdn.business.common.utils.JsonUtil;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author likun
 * @date 2022/12/29 11:42
 */
@Slf4j
public class SystemFeignErrorDecoder extends ErrorDecoder.Default {
    @Override
    public Exception decode(String methodKey, Response response) {
        Exception exception = super.decode(methodKey, response);
        log.error("SystemFeignErrorDecoder method:{} ex:{}", methodKey, JsonUtil.toJsonString(exception));
        if (exception instanceof FeignException) {
            int status = ((FeignException) exception).status();
            String content = ((FeignException) exception).responseBody().map(s -> StandardCharsets.UTF_8.decode(s).toString()).orElse("");
            if (StringUtils.isNotBlank(content)) {
                ApiErrorResult resp = JsonUtil.toBean(content, ApiErrorResult.class);
                if (StringUtils.isNotBlank(resp.getErrorCode())) {
                    throw new BusinessException(resp.getCode(), resp.getMsg(), resp.getErrorCode());
                }
            }
            return new BusinessException(status, ResultCodeEnum.THIRD_ERROR.getMsg());
        }
        return exception;
    }
}